package services

import (
	"context"
	"go.didapinche.com/foundation/plat-echo/app/ops/models"
	"go.didapinche.com/foundation/plat-echo/app/ops/repositories"
	dtime "go.didapinche.com/time"
	"go.uber.org/zap"
)

type DashboardService interface {
	Create(ctx context.Context, dashboard *models.Dashboard) (*models.Dashboard, error)
	FindAll(ctx context.Context) ([]*models.Dashboard, error)
	Update(ctx context.Context, dashboard *models.Dashboard) (*models.Dashboard, error)
	DeleteByID(ctx context.Context, ID uint64) error
}
type dashboardService struct {
	dashboardRepo   repositories.DashboardRepository
	logger          *zap.Logger
	graphRepository repositories.GraphRepository
}

func NewDashboardService(dashboardRepo repositories.DashboardRepository,
	graphRepository repositories.GraphRepository,
	logger *zap.Logger) DashboardService {
	return &dashboardService{
		dashboardRepo:   dashboardRepo,
		graphRepository: graphRepository,
		logger:          logger,
	}
}

func (d *dashboardService) Create(ctx context.Context, dashboard *models.Dashboard) (*models.Dashboard, error) {
	dashboard.CreateTime = dtime.Now()
	dashboard.UpdateTime = dtime.Now()
	err := d.dashboardRepo.Create(ctx, dashboard)
	if err != nil {
		return nil, err
	}
	return dashboard, nil
}

func (d *dashboardService) FindAll(ctx context.Context) ([]*models.Dashboard, error) {
	return d.dashboardRepo.FindAll(ctx)
}

func (d *dashboardService) Update(ctx context.Context, dashboard *models.Dashboard) (*models.Dashboard, error) {
	err := d.dashboardRepo.Update(ctx, dashboard)
	if err != nil {
		return nil, err
	}
	return dashboard, nil
}

func (d *dashboardService) DeleteByID(ctx context.Context, ID uint64) error {
	err := d.dashboardRepo.DeleteByID(ctx, ID)
	if err != nil {
		return err
	}
	//dashboards, err := d.dashboardRepo.FindByParentID(ctx, ID)
	//var ids []uint64
	//ids = append(ids, ID)
	//for _, dashboard := range dashboards {
	//	ids = append(ids, dashboard.ID)
	//}
	err = d.graphRepository.DeleteByDashboardID(ctx, ID)
	if err != nil {
		return err
	}
	return nil
}
